package com.galaxy.common.util.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.galaxy.common.util.string.StringUtil;
import com.galaxy.common.util.web.BrowserUtils;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String webroot_realpath = StringUtil.u2fPath(new File(request.getServletContext().getRealPath("")).getParent()) ;
		String filePath = request.getParameter("filePath") ;
		String fileName = request.getParameter("fileName") ;
		
		if(null != filePath && null != fileName) {
			
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;
			OutputStream fos = null;
			InputStream fis = null;
			
				try {
					fileName = URLDecoder.decode(fileName,"utf-8") ;
					
					File file = new File(webroot_realpath+filePath+File.separator+fileName);
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					fos = response.getOutputStream();
					bos = new BufferedOutputStream(fos);
					
					String downFileName = fileName ;
					
					// 处理中文
					if(BrowserUtils.isIE(request)){
						//IE下载，处理弹出框显示乱码
						downFileName = URLEncoder.encode(fileName,"UTF-8") ;
					} else {
						//FF下载，处理弹出框显示乱码
						downFileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
					}
					
					response.setContentType("application/x-download charset=UTF-8");
					response.setHeader("Content-disposition", "attachment;filename=" + downFileName);
					
					int bytesRead = 0;
					byte[] buffer = new byte[8192];
					while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
						bos.write(buffer, 0, bytesRead);
					}
				} catch (FileNotFoundException e) {
					response.setCharacterEncoding("UTF-8") ;
					response.getWriter().print("暂时无法进行多文件下载，多文件下载需进行打包，还没做。") ;
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if(null != bos) {
						bos.flush();
						if(null != fis) 
							fis.close();
						if(null != bis) 
							bis.close();
						if(null != fos) 
							fos.close();
						if(null != bos) 
							bos.close();
					}
				}
			
		}
		
		
	}
	
}
